package ru.pb.game.data.scripts;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * @author Felixx
 * @param <T>
 */
public class ScriptInstance<T>
{
	private static final Logger _log = Logger.getLogger(ScriptInstance.class);

	private final Class<T> _class;
	private final T _instance;

	public ScriptInstance(Class<T> c, T instance)
	{
		_class = c;
		_instance = instance;
	}

	public Object invoke(Method method, Object... arguments)
	{
		if(_class == null || _instance == null || method == null)
		{
			return null;
		}

		try
		{
			return method.invoke(Modifier.isStatic(method.getModifiers()) ? null : _instance, arguments);
		}
		catch(Exception e)
		{
			_log.info("Exception: " + method.getName() + " " + e, e);
		}

		return null;
	}

	public List<ScriptMethodInvoke> getMethodsByAnnotation(Class<? extends Annotation> c)
	{
		List<ScriptMethodInvoke> ms = new ArrayList<ScriptMethodInvoke>(0);
		for(Method method : _class.getMethods())
		{
			if(method.isAnnotationPresent(c) && method.getParameterTypes().length == 0)
			{
				ms.add(new ScriptMethodInvoke(this, method));
			}
		}

		return ms;
	}
}
